<?php


namespace app\admin\controller;


use app\api\service\JinDie;
use app\common\controller\AdminBaseController;
use app\common\model\tang\WatchLog;
use app\common\model\tang\WatchMaintain;
use app\common\model\tang\Merchant;
use app\common\energyApi\Energy;
use think\Db;
use app\common\model\tang\KwhLog;
use app\common\model\tang\MonthElectricityDegree;
use app\common\model\tang\MonthWaterLog;
use think\Exception;
use think\facade\Queue;


class WatchMaintainList extends AdminBaseController
{
    protected function initialize()
    {

        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new WatchMaintain();
        $this->Energy = new Energy();
    }


    public function index()
    {
        if (IS_AJAX) {
            return $this->model->getAdminPageData($this->param);
        }
        $merchant_list = getMerchant();
        //获取菜单列表
        $this->assign(compact("merchant_list"));
        return $this->fetch();
    }
    public function export(){

        $data = $this->model->with(['merchant'])->select()->toArray();
        $title = ['商户名','商户编号','合同号','设备类型','使用类型','设备编号','设备名称','倍率','是否特殊用表'];
        foreach ($data as $key => $value) {
            if($value['name']=='-'||empty($value['name'])){
                $merchant_name = $value['company'];
            }else{
                $merchant_name = $value['name'];
            }
            if($value['is_sole']==1) $isSole='是';
            if($value['is_sole']==0) $isSole='否';
            $use_type = '暂无配置';
            if($value['use_type']==1) $use_type='写字楼自用';
            if($value['use_type']==2) $use_type='写字楼公区';
            if($value['use_type']==3) $use_type='写字楼商户';
            if($value['use_type']==4) $use_type='商场自用';
            if($value['use_type']==5) $use_type='商场公区';
            if($value['use_type']==6) $use_type='商场商户';
            if($value['type']==1) $type='智能电表';
            if($value['type']==2) $type='智能水表';
            if($value['type']==3) $type='普通电表';
            if($value['type']==4) $type='普通水表';
            $export[$key]['merchant_name'] =$merchant_name;
            $export[$key]['merchant_sn'] ="\t".$value['merchant_sn']."\t";
            $export[$key]['code'] =  "\t".$value['code']."\t";
            $export[$key]['type'] =  $type;
            $export[$key]['use_type'] = $use_type;
            $export[$key]['pointId'] =  "\t".$value['pointId']."\t";
            $export[$key]['pointName'] = "\t".$value['pointName']."\t";
            $export[$key]['rate'] =$value['rate'];
            $export[$key]['is_sole'] = $isSole;
        }
        return export_excel('表号维护_'.date('Y-m-d'),$title,$export);
    }
    /**
     * 读取电表信息
     */
    public function getWatch(){
        $Energy = new Energy();
        $jin = new JinDie();
        $data = [];
//        $bang = $Energy->universalfunction('query_pointCustomer_info', []);
        $bang =  $jin->get_Points($data);
        if(empty($bang)){
            return self::JsonReturn("请再次点击获取最新表数据");
        }
        foreach ($bang as $key => $row) {
            $da = [
                'pointId'=>$row['commaddr'],
//                'hm'=>$row['hm'],
                'pointName'=>$row['name'],
                'point'=>$row['pointid'],
//                'status'=>$row['status'],
                'type'=>$row['energytypeid'],
//                'phone'=>$row['phone'],
//                'userId'=>$row['userId'],
                'rate'=>$row['rate']
            ];
            $where['point'] = $row['pointid'];
            $isfirst = (new WatchMaintain())->where($where)->find();
            if(empty($isfirst)){
                (new WatchMaintain)->save($da);
            }else{
                (new WatchMaintain())->update($da,['point'=>$isfirst['point']]);
            }
//            $this->upPointName($row['commaddr'],$row['energytypeid']);
        }
        return self::JsonReturn("同步成功");
    }
//    public function upPointName($userId,$pointType){
//        // 当轮到该任务时，系统将生成该类的实例，并调用其fire方法
//        $jobHandlerClassName = 'app\api\service\Jobs@PointName';
//        // 2.当任务归属的队列名称，如果为新队列，会自动创建
//        // 这个队列名称自由建立，最好和业务相关且不能重复，不然你懂的
//        $jobQueueName = "UpPointNameQueue";
//        $res['pointId'] = $userId;
//        $res['type'] = $pointType;
//        Queue::push($jobHandlerClassName, $res, $jobQueueName);
//    }
    /**
     * @return false|string 新增表号维护
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            if(!isset($data['id'])){
                $pointInfo = $this->model->where('pointId', $data['pointId'])->find();
                if ($pointInfo) {
                    return self::JsonReturn("设备编号不能重复", 0);
                }
            }
            return $this->model->doAll($data);
        }
        $id = $this->request->param("id/d");//父id
        $info = $this->model->find($id);
        //获取菜单列表
        $this->assign(compact("info", "id"));
        //获取商户列表
        $Merchant_list = getMerchant();
        $this->assign("merchant_list", $Merchant_list);
        return $this->fetch();
    }
    public function switching(){
        $id = $this->request->param("ids/d");//父id
        $info = $this->model->find($id);
        try {
            if($info['switching']==1){
                $operType = 1;
                $switching = 2;
            }else{
                $operType = 2;
                $switching = 1;
            }
            $Energy = new Energy();
            //拉闸
            $watch= new WatchLog();
            $data = [
                "pointId" => '000000332241',
                "operType" => $operType //1 拉闸2 合闸
            ];
            // 查询月电费接口
            $port_data = $Energy->universalfunction('remote_disconnect', $data);
            if(isset($port_data)){
                $watch->pointId = $data['pointId'];
                $watch->operType = $data['operType'];
                $watch->return_info = json_encode($port_data);
                $watch->create_time = time();
                $watch->save();
            }
            $this->model->where('id', $id)->update(['switching'=>$switching]);
            return json_encode(['code' => 1, "msg" => "处理成功"]);
        }catch (Exception $exception){
            return json_encode(['code' => 0, "msg" => $exception->getMessage()]);
        }


    }
    /**
     *检测表是否能正常使用
     */
    public function check()
    {
        $data = $this->request->param();
//        $pointInfo = $this->model->where('pointId', $data['pointId'])->find();
//        if ($pointInfo) return json_encode(['code' => -1, "msg" => "设备编号不能重复"]);
        $res = [
            'pointId' => $data['pointId']
        ];
        if ($data['type'] == 1) {
            $url = 'query_YWGPointPowerBm_info';
        } else {
            $url = 'query_YWGPointWaterBm_info';
        }
        $resdata = $this->Energy->universalfunction($url, $res);
        if ($resdata == false || empty($resdata)) {
            return json_encode(['code' => -1, "msg" => "请输入正确的设备编号"]);
        }
        return json_encode(['code' => 1, "msg" => "检测成功"]);
    }

    /**
     * @return false|string 启用停用此表
     */
    public function stop()
    {
        $param = request()->param();
        if (isset($param['id']) && !empty($param['id'])) {
            $list = $this->model->where('id', $param["id"])->field('status')->find()->toArray();
            $where = [];
            if (isset($list) && !empty($list)) {
                if ($list['status'] == "正常") {
                    $where = ['status' => 2];
                }
                if ($list['status'] == "停用") {
                    $where = ['status' => 1];
                }
                $res = $this->model->where('id', $param["id"])->update($where);
                if ($res) {
                    return json_encode(['code' => 1, "msg" => "停用成功"]);
                }
                return json_encode(['code' => 0, "msg" => "停用成功"]);
            }
            return json_encode(['code' => 0, "msg" => "请求数据不存在请重试！"]);
        }
        return json_encode(['code' => 0, "msg" => "请求错误！"]);
    }

    /**
     * @return mixed|void删除
     */
    public function del()
    {
        if (IS_AJAX) {
            $ids = $this->request->post("ids");
            $result = WatchMaintain::where('id', 'in', $ids)->delete();
            if ($result) {
                return self::JsonReturn("删除成功");
            } else {
                return self::JsonReturn("删除失败");
            }

        }
    }
}